package com.cskaoyan.wordmemorize.controller.admin;

import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.common.util.IpUtil;
import com.cskaoyan.wordmemorize.dto.admin.AdminLoginDTO;
import com.cskaoyan.wordmemorize.dto.admin.EmployeeDTO;
import com.cskaoyan.wordmemorize.request.EmployeeLoginRequest;
import com.cskaoyan.wordmemorize.service.EmployeeService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;


@RestController("adminLoginController")
public class LoginTestController {

    @Autowired
    EmployeeService employeeService;

    // 处理登录请求
    @PostMapping("admin/login")
    public Result<AdminLoginDTO> login(@RequestBody EmployeeLoginRequest request,  HttpServletRequest servletRequest) {

        EmployeeDTO employee = employeeService.login(request.getUsername(), request.getPassword());


        // 2. 使用sa-token的login方法开启会话(注意使用后台账号的StpLogic对象)
        // 用用户id为账号id，开启了用户会话
        StpKit.ADMIN.login(employee.getId());

        // 3. 更新员工登录时间，登录ip
        String ipAddr = IpUtil.getIpAddr(servletRequest);
        Long id = Long.parseLong(employee.getId());
        // 大家自己实现单表更新
        employeeService.updateLoginInfo(id, ipAddr, LocalDateTime.now());

        // 4. 获取会话id(即会话对应的tokenValue)，并返回
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
        // 获取会话对应的唯一表示值
        String tokenValue = StpKit.ADMIN.getTokenValue();
        adminLoginDTO.setToken(tokenValue);

        return Result.ok(adminLoginDTO);
    }
    //后台员工登出
    @PutMapping("admin/logout")
    public Result<String> logout() {
        StpKit.ADMIN.logout();
        return Result.ok("登出成功");
    }


}
